package com.pfizer.pfizerExpertForPad;

import java.io.InputStream;
import java.net.URL;
import java.util.List;

import com.pfizer.DB.DataHelper;
import com.pfizer.Entity.pMessage;
import com.pfizer.Public.PublicFunc;
import com.pfizer.XmlContentHandler.SaxReadXml;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

/**
 * MsgSyncService--<b>系統訊息同步服務</b> 同步系統相關訊息，及時顯示
 * 
 * @author krui
 * @version 2.0 2011/11/22
 */
public class MsgSyncService extends Service {

	// 定義同步服務器連接字符串
	private static final String MsgUrlFormat = "%s/Pens_Api/Query.aspx?ProveCode=%s&Obj_From=%s&Obj_ID=%s&Which=Msg_ReceiverGet&UserID=%s";
	private static final String MsgUrlChkFormat = "%s/Pens_Api/Query.aspx?ProveCode=%s&Obj_From=%s&Obj_ID=%s&Which=Msg_ReceiverGet_Check&UserID=%s&Msg_ID=%s";

	private DataHelper dHelper;
	pfizerApplication pApplication;
	Context mcontext = null;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * onCreate：創建服務時發生
	 * 
	 * @see android.app.Service#onCreate()
	 * @see com.pfizer.pfizerExpertForPad.pfizerApplication
	 * @see com.pfizer.DB.DataHelper
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		mcontext = MsgSyncService.this;
		InitApp initApp = new InitApp(mcontext);
		initApp.SetApp(0);
		pApplication = (pfizerApplication) mcontext.getApplicationContext();
		dHelper = pApplication.getDataHelper();
	}

	/**
	 * onStart：啟動服務時發生，同步訊息
	 * 
	 * @see android.app.Service#onStart(android.content.Intent, int)
	 */
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		SysnMsg();

	}

	/**
	 * 將字節流轉變為字符（工具方法）
	 * 
	 * @param in
	 * @return
	 * @throws IOException
	 */

	/**
	 * 同步發送已經查看的訊息
	 * 
	 */

	private void SyncSendCheckMsg() {

		try {
			// 根據USERID獲取已經查看的訊息
			String sTmp = dHelper.getNeedCheckMsgIDByUserID(pApplication
					.getUserID());
			if (sTmp.length() > 0) {
				String urlStr = String.format(MsgUrlChkFormat, pApplication
						.getWebUrl(), pApplication.getMainProveCode(),
						pApplication.getObjFrom(), pApplication.getObjID(),
						pApplication.getUserID(), sTmp);
				URL url = new URL(urlStr);
				InputStream inputStream = url.openStream();
				if (PublicFunc.inputStream2String(inputStream)
						.equalsIgnoreCase("Y")) {
					// 如果獲取到的字符為Y，則已經查看，更新本地數據
					dHelper.updateMessageFlag(pApplication.getUserID(), 3);
				}
			}
		} catch (Exception ex) {
			return;
		}
	}

	/**
	 * 從服務器上同步新訊息
	 */
	private void SysnAcceptMsg() {
		InputStream inputStream = null;
		// 訊息地址字符串
		String urlStr = String.format(MsgUrlFormat, pApplication.getWebUrl(),
				pApplication.getMainProveCode(), pApplication.getObjFrom(),
				pApplication.getObjID(), pApplication.getUserID());
		// urlStr="http://lab.sicnu.edu.cn/xml/message.xml";
		try {
			URL url = new URL(urlStr);
			inputStream = url.openStream();
		} catch (Exception ex) {
			return;
		}
		// 獲取訊息
		try {
			List<pMessage> msgList = SaxReadXml.readMessage(inputStream);
			int iLen = msgList.size();
			pMessage msg;
			for (int i = 0; i < iLen; i++) {
				msg = msgList.get(i);
				msg.setUserID(pApplication.getUserID());
				// 如果本地不存在此信息，就是獲取的最新數據將之就存入本地
				if (!dHelper.isExistsMessageByMsgIDAndUserID(msg.getMsgID(),
						msg.getUserID())) {
					dHelper.addMessage(msg);
				}
			}
		} catch (Exception ex) {
			return;
		}
	}

	/**
	 * 訊息同步線程
	 */
	private void SysnMsg() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					SyncSendCheckMsg();
					SysnAcceptMsg();
					// 是新訊息就到訊息介面處理
					if (dHelper.isNewMessageByUserID(pApplication.getUserID())) {
						Intent i = new Intent(mcontext, MessageActivity.class);
						i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						mcontext.startActivity(i);
					}
				} catch (Exception ex) {
					return;
				}
			}
		}).start();
	}

}
